<template>
  <div class="view-wrapper">
    <div class="main">
      <div class="main_title">{{title}}</div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" class="demo-ruleForm">
        <el-row>
          <el-col :span="20">
            <el-form-item label="标题：" prop="title">
              <el-input v-model="ruleForm.title" maxlength="40" placeholder="请填写标题" >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="排序：" prop="sort">
              <el-input v-model="ruleForm.sort" maxlength="20" placeholder="请填写排序" >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="活动时间：" prop="time">
              <el-date-picker v-model="ruleForm.time" type="datetime" range-separator="至" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="公告弹窗日期：" prop="date">
              <el-date-picker v-model="ruleForm.date" type="daterange" value-format="yyyy-MM-dd" size="small" range-separator="至" 
                start-placeholder="开始日期" end-placeholder="结束日期" @change="handleTime">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        
       
        <el-form-item label="公告隐藏：" prop="status">
          <el-switch active-text="显示" inactive-text="隐藏" v-model="ruleForm.status" active-value="1" inactive-value="2">
          </el-switch>
        </el-form-item>
        <el-form-item label="公告内容：" prop="content">
          <div class="richText">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="ruleForm.content" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="onCreated"  @onChange="onChange"/>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')" v-if="pathType == 'add'" :loading="submitLoading">保存提交
          </el-button>
          <el-button type="primary" @click="editForm('ruleForm')" v-if="pathType == 'edit' " :loading="submitLoading">保存提交
          </el-button>
          <el-button @click="clickBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
  import {
    addAnnouncement,
    getInfo,
    editAnnouncement
  } from "@/api/announcement";
  import '@wangeditor/editor/dist/css/style.css'
  import {
    Editor,
    Toolbar
  } from "@wangeditor/editor-for-vue";
  export default {
    components: {
      Editor,
      Toolbar
    },
    data() {
      return {
        submitLoading: false,
        title: '新增文章',
        pathType: 'add',
        action: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile",
        ruleForm: {
          //   delivery: true,
          title: '',//活动名称
          id: '', 
          sort: '',//排序
          status: '1', //状态 1显示 2隐藏
          time: '', //活动开始时间
          content: '',//内容
          popStartTime: '',
          popEndTime: '',
          date: [],
        },
        rules: {
          title: [{
            required: true,
            message: '请输入标题',
            trigger: 'blur'
          }],
          sort: [{
            required: true,
            message: '请输入排序',
            trigger: 'blur'
          }],
          time: [{
            required: true,
            message: '请选择时间',
            trigger: 'change'
          }],
          date: [{
            required: true,
            message: '请选择时间',
            trigger: 'change'
          }],
          status: [{
            required: true,
            message: '请选择状态',
            trigger: 'change'
          }],
          content: [{
            required: true,
            message: '请输入内容',
            trigger: 'blur'
          }],

        },
        // 富文本配置
        logoUploadUrlImg: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile", //图片接口
        videoUploadUrl: process.env.VUE_APP_BASE_API + "/common/v1/uploadFile", //视频接口
        editor: null,
        html: "<p>hello&nbsp;world</p>",
        toolbarConfig: {
          // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
          // excludeKeys: [ /* 隐藏哪些菜单 */ ],
          excludeKeys:['group-video']
        },
        editorConfig: {

          placeholder: "请输入内容...",
          // autoFocus: false,
          // 所有的菜单配置，都要在 MENU_CONF 属性下
          MENU_CONF: {},
        },
        mode: 'default', // or 'simple'
      };
    },
    created() {
      
      var _this = this
      // 配置上传图片
      var name = ''
      this.editorConfig.MENU_CONF['uploadImage'] = {
        server: _this.logoUploadUrlImg,
        // headers: _this.headers,
        fieldName: 'file',
        //    async customUpload(file, insertFn) {
        //        console.log(file)
        //     // file 即选中的文件
        //     // 自己实现上传，并得到图片 url alt href
        //     // 最后插入图片
        //     //   insertFn(url, alt, href)
        //     },
        onSuccess(file, res) {
          name = file.name
          // console.log(`${file.name} 上传成功`, res)
        },
        customInsert(res, insertFn) {
          console.log(res)
          insertFn(res.result.url, name, res.result.url)
        }
      }
      // 配置上传视频
      this.editorConfig.MENU_CONF['uploadVideo'] = {
        server: _this.videoUploadUrl,
        // headers: _this.headers,
        fieldName: 'file',
        maxFileSize: 500 * 1024 * 1024,
        //    async customUpload(file, insertFn) {
        //        console.log(file)
        //     // file 即选中的文件
        //     // 自己实现上传，并得到图片 url alt href
        //     // 最后插入图片
        //     //   insertFn(url, alt, href)
        //     },
        customInsert(res, insertFn) {
          // res 即服务端的返回结果
          // 从 res 中找到 url ，然后插入
          insertFn(res.result.url)
        },
      }
      const query = this.$route.query
      this.pathType = query.pathType
      if (this.pathType == 'edit') {
        
        this.title = '编辑文章'
        setTimeout(() => {
          this.getInfo(query.id)
        }, 100)
      }
    },
    mounted() {
      
    },
    methods: {
      onCreated(editor) {
        this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
        console.log('this.editor',this.editor)
      },
      onChange(editor) {
        console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
      },
      getEditorText() {
        const editor = this.editor;
        if (editor == null) return;

        console.log(editor.getText()); // 执行 editor API
      },
      printEditorHtml() {
        const editor = this.editor;
        if (editor == null) return;

        console.log(editor.getHtml()); // 执行 editor API
      },
      getInfo(id) { //获取编辑详情
        getInfo(id).then((res) => {
          this.ruleForm.content = res.result.content
          this.ruleForm  = {
            title: res.result.title,//活动名称
            id: res.result.id, 
            sort: res.result.sort,//排序
            status: res.result.status, //状态 1显示 2隐藏
            time: res.result.time, //活动开始时间
            content: res.result.content,//内容
            popStartTime: res.result.popStartTime,
            popEndTime: res.result.popEndTime,
            date: [],
          }
          this.ruleForm.date[0] = res.result.popStartTime
          this.ruleForm.date[1] = res.result.popEndTime 
          
        });
      },
      handleTime(e){
        console.log('e',e)
        this.ruleForm.popStartTime = e[0]
        this.ruleForm.popEndTime = e[1]
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          console.log('this.ruleForm',this.ruleForm)
          if (valid) {
            // this.shopTypeIdList
            console.log('成功', this.ruleForm)
            this.submitLoading = true
            // return
            var params = {
              ...this.ruleForm,
            }
            addAnnouncement(params).then((res) => {
                this.$message({
                  message: "创建成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.submitLoading = false
                  this.$router.push({
                    path: "/incentiveManagement/announcement-list",
                  });
                }, 1000);
              })
              .finally(() => {
                setTimeout(() => {
                  this.submitLoading = false;
                }, 1000)
              });
          } else {
            console.log('error submit!!', this.ruleForm);
            return false;
          }
        });
      },
      editForm(formName) { //编辑
        this.$refs[formName].validate((valid) => {
          console.log(valid)
          if (valid) {
            this.submitLoading = true
            var params = {
              ...this.ruleForm,
            }
            editAnnouncement(params).then((res) => {
                this.$message({
                  message: "编辑成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.submitLoading = false
                  this.$router.push({
                    path: "/incentiveManagement/announcement-list",
                  });
                }, 1000);
              })
              .finally(() => {
                setTimeout(() => {
                  this.submitLoading = false;
                }, 1000)
              });
          } else {
            console.log('error submit!!', this.ruleForm);
            return false;
          }
        });
      },
      resetForm(formName) { //重置
        this.$refs[formName].resetFields();
      },
      clickBack() { //返回
        this.$router.go(-1)
      },
    }
  }

</script>
<style scoped>
  .main {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px 20px;
    margin-top: 10px;
  }

  .main_title {
    margin-bottom: 20px;
    font-weight: bold;
  }

  .lable_title {
    font-size: 14px;
    color: #606266;
    margin-right: 10px;
  }

  .lable_title_end {
    font-size: 14px;
    color: #606266;
    margin-left: 10px;
  }

  .flex {
    display: flex;
    align-items: centerf;
  }
  .richText {
    border: 1px solid #ccc;
    line-height: normal;
  }
  /* .el-input {
    width: 300px !important;
  } */

</style>
